package cn.livingCloud.controller.core.validator;

import cn.livingCloud.dto.EmployeeFormDto;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.util.regex.Pattern;

/**
 * Created by DingJie  on 2016/5/27.
 */
@Component
public class EmployeeFormDtoValidator implements Validator {
    public static final String PHONE_REGULAR = "1[0-9]{10}";

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return EmployeeFormDto.class.equals(aClass);
    }

    @Override
    public void validate(Object target, Errors errors) {
        EmployeeFormDto formDto = (EmployeeFormDto) target;
        validateTitleAndContent(formDto, errors);
        validatePhone(formDto, errors);
        validateAge(formDto, errors);
    }

    private void validateTitleAndContent(EmployeeFormDto formDto, Errors errors) {
        if (StringUtils.isEmpty(formDto.getName())) {
            errors.rejectValue("name", null, "请填写姓名");
        }
        if (StringUtils.isEmpty(formDto.getGender())) {
            errors.rejectValue("gender", null, "请选择性别");
        }

        if (StringUtils.isEmpty(formDto.getDeptUuid())) {
            errors.rejectValue("deptUuid", null, "请选择部门");
        }
    }

    private void validateAge(EmployeeFormDto formDto, Errors errors) {
//        if (StringUtils.isEmpty(formDto.getAge())) {
//            errors.rejectValue("age", null, "请输入年龄");
//        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(formDto.getAge()) && !isInteger(formDto.getAge())) {
            errors.rejectValue("age", null, "请输入正确数字");
        }
    }

    private void validatePhone(EmployeeFormDto formDto, Errors errors) {
//        if (StringUtils.isEmpty(formDto.getPhone())) {
//            errors.rejectValue("phone", null, "请填写手机号码");
//            return;
//        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(formDto.getPhone()) && !validateIsPhoneNumber(formDto)) {
            errors.rejectValue("phone", null, "请输入正确的手机号!");
        }
    }

    private boolean validateIsPhoneNumber(EmployeeFormDto formDto) {
        return Pattern.compile(PHONE_REGULAR).matcher(formDto.getPhone()).matches();
    }

}
